<?php


namespace Aoe\Attributes\Container;

use Aoe\Attributes\ParameterInterface;
use Aoe\Core\Kernel;
use Attribute;
use ReflectionParameter;
use Throwable;

/**
 * # 依赖注入
 */
#[Attribute(Attribute::TARGET_PARAMETER)]
class Dependent implements ParameterInterface
{
    public function __construct(protected ?string $key = null) {}
    
    public function forParameters(Kernel $kernel, ReflectionParameter $parameter, array &$args): bool
    {
        try {
            $args[] = $kernel->container->get($this->key ?? $parameter->getType());
            return true;
        } catch (Throwable) {
            return false;
        }
    }
}